import os,sys,random,pygame,math
from pygame.locals import *
import cPickle as pickle

import screen

def load_image(name,colorkey):
    fullname = os.path.join('data','pictures',name)
    i=pygame.image.load(fullname)
    if colorkey==0:
        colorkey=None
    if colorkey is not None:
        if colorkey is -1:
            colorkey = i.get_at((0,0))
        i.set_colorkey(colorkey, RLEACCEL)
    return i.convert()

class LevelController:
    def __init__(self,image,world,blocktype,specials,text,start):
        self.world = world
        self.blocktype = blocktype
        self.specials = specials
        self.text = text
        self.start_position = start

        self.image,self.overlay,self.rect = self.make_image(image)

    def make_image(self,image):
        if self.world == 'W1':
            BS1 = load_image('W1BS1.png',0)
            DB1 = load_image('W1DB1.png',0)
            CB1 = load_image('W1CB1.png',-1)
            WB1 = load_image('W1WB1.png',0)
        temprect = image.get_rect(topleft = (0,0))
        width = temprect.width
        height = temprect.height
        newimage = pygame.Surface((int(width*64),int(height*64)))
        overlay = pygame.Surface((int(width*64),int(height*64)))
        rect = newimage.get_rect(topleft = (0,0))
        newimage.fill((255,255,255))
        overlay.fill((200,200,200))
        for y in range(height):
            for x in range(width):
                color = image.get_at((x,y))
                newx = x * 64
                newy = y * 64
                pict = pygame.Surface((64,64))
                pict.fill(color)
                newimage.blit(pict,(newx,newy))
                if color == (0,0,0):
                    overlay.blit(BS1,(newx,newy))
                elif color == (255,0,0):
                    overlay.blit(DB1,(newx,newy))
                elif color == (0,255,0):
                    overlay.blit(CB1,(newx,newy))
                elif color == (0,0,255):
                    overlay.blit(WB1,(newx,newy))

        return newimage,overlay,rect

    def move(self,move):
        self.rect = self.rect.move(move)
        for spec in self.specials:
            spec.move(move)

    def update(self):
        screen.screen.blit(self.overlay,self.rect)
        for spec in self.specials:
            spec.update()

    def start_pos(self):
        return self.start_position

    def reset(self):
        move = (0,0)
        m = self.rect.topleft
        if m[0] < 0:
            x = abs(m[0])
        else:
            x = -m[0]
        if m[1] > 0:
            y = abs(m[1])
        else:
            y = -m[1]
        move = (x,y)
        self.move(move)
